package com.cavy.platform.server.domain.job;

import com.cavy.platform.server.domain.Agent;
import com.cavy.platform.server.domain.message.ContainerExecutedSuccessMessage;
import com.cavy.platform.server.domain.message.JobMessageSubscribe;
import com.cavy.platform.server.domain.message.StageExecutedSuccessMessage;
import com.cavy.platform.server.mapper.AgentMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class RunningJob extends AbstractJobAction {
    private JobAgent info;

    public RunningJob() {
    }

    public RunningJob(Job job, Agent info) {
        super(job);
        this.info = AgentMapper.INSTANCE.toJobAgent(info);
    }

    @JobMessageSubscribe
    public void containerExecutedSuccess(ContainerExecutedSuccessMessage message) {
        getContainer(message.getStageName(), message.getIndex()).setStatus(JobStageStatus.EXECUTION);
        save(this);
        sendJob();
    }

    @JobMessageSubscribe
    public void stageExecutedSuccess(StageExecutedSuccessMessage message) {
        getStage(message.getStageName()).setStatus(JobStageStatus.EXECUTION);
        save(this);
        sendJob();
    }

    @Override
    public void initJobStatus() {
        this.job.status = JobStatus.RUNNING;
        JobStage jobStage = this.job.jobStageList.get(0);
        jobStage.setStatus(JobStageStatus.EXECUTING);
        for (JobContainer container : jobStage.getContainerList()) {
            container.setStatus(JobStageStatus.EXECUTING);
        }
    }
}
